package com.data.algorithm.sort;

/**
 * 归并排序
 *
 * @author wangjie
 * @version V1.0
 * @date 2020/3/25
 */
public class MergetSort {



    public static void main(String[] args) {
        int[] arr = new int[8000000];

        for (int i = 0; i < 8000000; ++i) {
            arr[i] = (int) (Math.random() * 80000000.0D);
        }
        int[] temp = new int[arr.length];
        Long startTime = System.currentTimeMillis();
        System.out.println("开始排序");
        mergeSort(arr,0,arr.length-1,temp);
        Long endTime = System.currentTimeMillis() - startTime;

        System.out.println("排序耗时：" + endTime + "毫秒");
        System.out.println("排序耗时：" + endTime / 1000 + "秒");
    }

    /**
     * 归并排序--归并
     * @param arr
     * @param left
     * @param right
     * @param temp
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }

    }

    /**
     * 归并排序--排序
     * @param arr
     * @param left
     * @param mid
     * @param right
     * @param temp
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int t = 0;

        while(i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                ++t;
                ++i;
            } else {
                temp[t] = arr[j];
                ++t;
                ++j;
            }
        }

        while(i <= mid) {
            temp[t] = arr[i];
            ++t;
            ++i;
        }

        while(j <= right) {
            temp[t] = arr[j];
            ++t;
            ++j;
        }

        t = 0;

        for(int tempLeft = left; tempLeft <= right; ++tempLeft) {
            arr[tempLeft] = temp[t];
            ++t;
        }

    }
}
